package com.example.supermarket.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.supermarket.PageModel;
import com.example.supermarket.Result;
import com.example.supermarket.entity.Employee;
import com.example.supermarket.entity.Goods;
import com.example.supermarket.service.EmployeeService;
import com.example.supermarket.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hpp
 * @since 2021-10-26
 */
@RestController
@RequestMapping("/employee")
@CrossOrigin
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;
    /*添加员工*/
    @PostMapping("")
    public Result<Employee> addEmployee(@RequestParam("epName") String epName,
                                        @RequestParam("epJob") String epJob,
                                        @RequestParam("epPhoto") String epPhoto,
                                        @RequestParam(value="epPaiban", required = false,defaultValue = "") String epPaiban,
                                        @RequestParam(value="epMobile", required = false,defaultValue = "") String epMobile,
                                        @RequestParam(value="epEmail",required = false,defaultValue = "") String epEmail){
        Employee employee = new Employee();
        employee.setEpName(epName);
        employee.setEpJob(epJob);
        employee.setEpPhoto(epPhoto);
        employee.setEpMobile(epMobile);
        employee.setEpEmail(epEmail);
        employee.setEpPaiban(epPaiban);
        System.out.println(epPaiban);
        /*将时间错转换为本地日期时间*/
//        if (epPaiban.length() != 0){
//            Long ll = new Long(epPaiban);
//            Instant instant = Instant.ofEpochMilli(ll);
//            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
//            employee.setEpPaiban(localDateTime);
//        }
        boolean save = employeeService.save(employee);
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ep_name",employee.getEpName())
                .eq("ep_job",employee.getEpJob());
        Employee one = employeeService.getOne(queryWrapper);
        if (save) {
            return new Result<Employee>(200,"ok",one);
        }
        return new Result<Employee>(0,"error",null);
    }
    /*添加员工照片，并返回图片的本地存储路径url*/
    @PostMapping("/pics")
    public Result<String> addPic(@RequestParam("file") MultipartFile file) throws Exception{
        String folder= "D:\\supermarket\\image";
        File imageFolder = new File(folder);
        /*如果不存在该路径则创建*/
        if(!imageFolder.exists()){
            imageFolder.mkdirs();
        }
        /*使用唯一的名字命名图片名称*/
        String uniName = UUID.randomUUID() + file.getOriginalFilename();
        String fullName = folder +'/' + uniName;
        File f = new File(fullName);
        /*将前端传来的文件保存到相应的路径中*/
        try {
            file.transferTo(f);
            System.out.println(f.getAbsolutePath() + "保存成功！");
            String nameUrl = "http://localhost:8082/api/file/" + uniName;
            return new Result<String>(200,"ok",nameUrl);
        }catch(IllegalStateException e){
            e.printStackTrace();
        }catch(IOException el){
            el.printStackTrace();
        }
        /*添加失败或者遇到异常返回*/
        return new Result<>(0,"error",null);
    }
    /*分页查询员工信息，包括模糊查询*/
    @GetMapping("")
    public Result<PageModel<Employee>> getEmployee(@RequestParam (value = "query",required = false,defaultValue = "") String query,
                                        @RequestParam("pagenum") Integer pagenum,
                                        @RequestParam("pagesize") Integer pagesize){
        IPage<Employee> ipage = new Page<>(pagenum,pagesize);
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("ep_name",query);
        IPage<Employee> page  = employeeService.page(ipage,queryWrapper);
        PageModel<Employee> employeeResult = new PageModel<>(page.getTotal(),page.getCurrent(),page.getRecords());
        return new Result<>(200,"ok",employeeResult);
    }
    /*根据id获取员工信息*/
    @GetMapping("/{id}")
    public Result<Employee> getEmployeeById(@PathVariable Integer id){
        Employee byId = employeeService.getById(id);
        if (byId != null) {
            return new Result<Employee>(200,"ok",byId);
        }
        return new Result<Employee>(0,"error",null);
    }
    /*修改员工信息*/
    @PutMapping("")
    public Result<Employee> modifyEmployee(@RequestParam("epId") Integer epId,
                                           @RequestParam("epName") String epName,
                                           @RequestParam("epJob") String epJob,
                                           @RequestParam("epPhoto") String epPhoto,
                                           @RequestParam("epPaiban") String epPaiban,
                                           @RequestParam("epMobile") String epMobile,
                                           @RequestParam("epEmail") String epEmail){
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ep_id",epId)
                .set("ep_name",epName)
                .set("ep_job",epJob)
                .set("ep_photo",epPhoto)
                .set("ep_paiban",epPaiban)
                .set("ep_mobile",epMobile)
                .set("ep_email",epEmail);


        boolean update = employeeService.update(updateWrapper);
        Employee byId = employeeService.getById(epId);
        if (update) {
            return new Result<Employee>(200,"ok",byId);
        }
        return new Result<Employee>(0,"error",null);
    }

    /*删除员工*/
    @DeleteMapping("{id}")
    public Result<Employee> deleteEmployee(@PathVariable Integer id){
        boolean b = employeeService.removeById(id);
        if (b) {
            return new Result<Employee>(200,"ok",null);
        }
        return new Result<Employee>(0,"error",null);
    }
}

